from exchange_manager import ExchangeManager
from loguru import logger
import os
from dotenv import load_dotenv

def demo_public_api(manager, symbol="BTC/USDT:USDT"):
    """演示公共API功能"""
    logger.info("=== 演示公共API功能 ===")
    
    for exchange_id, exchange in manager.get_all_exchanges().items():
        try:
            # 1. 获取最新价格
            ticker = exchange.fetch_ticker(symbol)
            logger.info(f"{exchange_id} {symbol} 最新价格: {ticker['last']}")
            
            # 2. 获取订单簿深度
            orderbook = exchange.fetch_order_book(symbol)
            logger.info(f"{exchange_id} {symbol} 买一价: {orderbook['bids'][0][0] if orderbook['bids'] else 'N/A'}")
            logger.info(f"{exchange_id} {symbol} 卖一价: {orderbook['asks'][0][0] if orderbook['asks'] else 'N/A'}")
            
            # 3. 获取最近的成交
            trades = exchange.fetch_trades(symbol, limit=1)
            if trades:
                logger.info(f"{exchange_id} {symbol} 最近成交价格: {trades[0]['price']}")
                
        except Exception as e:
            logger.error(f"{exchange_id} 获取市场数据失败: {str(e)}")

def demo_private_api(manager):
    """演示私有API功能"""
    logger.info("\n=== 演示私有API功能 ===")
    
    # 加载环境变量
    load_dotenv()
    
    # 配置Gate.io API（作为示例）
    api_key = os.getenv('GATEIO_API_KEY')
    api_secret = os.getenv('GATEIO_SECRET')
    
    if not api_key or not api_secret:
        logger.warning("未找到API密钥，跳过私有API演示")
        return
    
    # 初始化私有API
    if manager.init_private_api('gateio', api_key, api_secret):
        exchange = manager.get_exchange('gateio')
        try:
            # 1. 获取账户余额
            balance = exchange.fetch_balance()
            total_usdt = balance.get('USDT', {}).get('total', 0)
            logger.info(f"Gate.io USDT余额: {total_usdt}")
            
            # 2. 获取当前持仓
            positions = exchange.fetch_positions()
            if positions:
                logger.info("当前持仓:")
                for pos in positions:
                    if float(pos['contracts']) > 0:
                        logger.info(f"交易对: {pos['symbol']}, 数量: {pos['contracts']}, 方向: {pos['side']}")
            
        except Exception as e:
            logger.error(f"获取账户信息失败: {str(e)}")

def main():
    # 创建交易所管理器实例
    manager = ExchangeManager()
    
    # 演示公共API功能
    demo_public_api(manager)
    
    # 演示私有API功能
    demo_private_api(manager)

if __name__ == "__main__":
    main() 